package com.yanqu.road.web.controller.chargecenter;

import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.web.controller.BaseHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/androidchargeNotify")
public class TestAndroidChargeNotify extends BaseHttpServlet {

	private static final long serialVersionUID = -4145213831008546653L;

	private static Logger logger = LogManager.getLogger(TestAndroidChargeNotify.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String customInfo = URLDecoder.decode(request.getParameter("custominfo"), "utf-8");
		int serverId = Integer.parseInt(request.getParameter("serverid"));

		ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
		if (serverInfo == null) {
			logger.error("ChargeCenter找不到serverId{}", serverId);
			sendMessage(response, "101");
			return;
		}

		// 转发消息到对应的服务器上
		Map<String, String> paramMap = new HashMap<>();
		paramMap.put("custominfo", customInfo);
		String result = HttpHelper.doGet(serverInfo.getWebServerUrl() + "/androidcharge", paramMap, "UTF-8");
		sendMessage(response, result);
	}
}
